const heartbeat = "heartbeat";//心跳信息
const { setChatMsg, getChatMsg } = require("../serviceRedis/chat");
const { verify } = require("../utils/jwt");
const uuid = require("uuid");
const chatWsClinet = {}
module.exports = {
    chatWs: (ws, ctx) => {
        const clinetId = uuid.v4();
        var tokenDataId;
        ws.on('message', async function (message) {
            if (message != heartbeat) {
                try {
                    var data = JSON.parse(message);
                    let { token, msg, time, once } = data;
                    var tokenData = verify(token)
                    if (tokenData) {
                        if (once == 1) {//第一次链接进入后存入信息
                            tokenDataId = tokenData.id;
                            if (!chatWsClinet[tokenDataId]) {
                                chatWsClinet[tokenDataId] = []
                            }
                            chatWsClinet[tokenDataId].push({
                                username: tokenData.username,
                                uuid: clinetId,
                                id: tokenDataId,
                                ws: ws
                            })
                        } else {
                            var data = {
                                username: tokenData.username,
                                msg,
                                time,
                                serveTime: new Date().getTime()
                            }
                            setChatMsg(tokenData.id, data)
                            chatWsClinet[tokenData.id].forEach(element => {
                                if (element.uuid != clinetId) {
                                    element.ws.send(JSON.stringify(data))
                                }
                            });
                        }
                    }
                    // var list = await getChatMsg(tokenData.id);
                    // list = list.map(element => {
                    //     return JSON.parse(element)
                    // });
                } catch (error) {
                    console.log(error)
                }
            }
        });
        ws.on('close', function () {
            if (chatWsClinet[tokenDataId]) {
                chatWsClinet[tokenDataId] = chatWsClinet[tokenDataId].filter(item => item.uuid != clinetId);
                console.log("用户id为" + tokenDataId + "退出;")
            }
        })
    }
}